package com.ctw.tinyservices.id.sdk.segment.service;

import com.alibaba.fastjson.JSON;
import com.ctw.tinyservices.id.common.entity.IdSegment;
import com.ctw.tinyservices.id.common.exception.HttpException;
import com.ctw.tinyservices.id.sdk.enums.HttpMethodEnum;
import com.ctw.tinyservices.id.sdk.util.OkHttpUtils;
import com.ctw.tinyservices.id.sdk.util.ServerLoadBalanceUtils;
import com.ctw.tinyservices.id.core.segment.service.IdSegmentService;
import com.google.common.base.Strings;
import java.util.List;
import java.util.Map;

/**
 * @author TongWei.Chen 2022/3/23 20:53
 *
 * IdSegmentHttpService
 **/
public class IdSegmentHttpService implements IdSegmentService {

    @Override
    public List<IdSegment> list() {
        return null;
    }

    @Override
    public IdSegment updateMaxIdAndGet(String bizType) {
        String url = ServerLoadBalanceUtils.getUrl(HttpMethodEnum.UPDATE_MAXID_AND_GET);
        Map<String, String> param = HttpMethodEnum.getUpdateMaxIdAndGetParam(bizType);
        String response = OkHttpUtils.post(url, param, ServerLoadBalanceUtils.getHeader());
        if (Strings.isNullOrEmpty(response)) {
            throw new HttpException(url, JSON.toJSONString(param));
        }
        return JSON.parseObject(response, IdSegment.class);
    }

    @Override
    public IdSegment updateMaxIdByStepAndGet(String bizType, int nextStep) {
        String url = ServerLoadBalanceUtils.getUrl(HttpMethodEnum.UPDATE_MAXID_BY_STEP_AND_GET);
        Map<String, String> param = HttpMethodEnum.getUpdateMaxIdByStepAndGetParam(bizType, nextStep);
        String response = OkHttpUtils.post(url, param, ServerLoadBalanceUtils.getHeader());
        if (Strings.isNullOrEmpty(response)) {
            throw new HttpException(url, JSON.toJSONString(param));
        }
        return JSON.parseObject(response, IdSegment.class);
    }
}